// components/blog-ctrl/blog-ctrl.js
let userInfo = {}

const db = wx.cloud.database()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blogId: String,
    blog: Object
  },

  options: {
    styleIsolation: 'apply-shared',
    multipleSlots: true
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 是否显示登陆组件
    loginShow: false,
    modalShow: false,
    content: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onComment() {
      // 判断用户是否授权
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: (res) => {
                userInfo = res.userInfo
                // 显示评论
                this.setData({
                  modalShow: true
                })
              }
            })
          } else {
            this.setData({
              loginShow: true
            })
          }
        }
      })
    },
    onLoginSuccess(event) {
      userInfo = event.detail
      // 授权框消失
      this.setData({
        loginShow: false
      }, () => {
        this.setData({
          modalShow: true
        })
      })
    },
    onLoginFail() {
      wx.showModal({
        title: '需授权才能评论',
        content: '',
      })      
    },
    onSend(event) {
      let content = event.detail.value.content
      let formId = event.detail.formId
      if (content.trim() === '') {
        wx.showModal({
          title: '评论内容不为空',
          content: '',
        })
        return
      }
      wx.showLoading({
        title: '评价中',
        mask: true
      })
      db.collection('blog-commend').add({
        data: {
          content,
          createTime: db.serverDate(),
          blogId: this.properties.blogId,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        }
      }).then((res) => {
        wx.hideLoading()
        wx.showToast({
          title: '评论成功'
        })
      })
      this.setData({
        modalShow: false,
        content: ''
      })

      // 刷新评论
      this.triggerEvent('refreshCommentList')
    },
  }
})
